package com.bing.habit.service.impl;

import com.bing.habit.entity.ClockinLog;
import com.bing.habit.entity.ClockinRecord;
import com.bing.habit.exception.BusinessException;
import com.bing.habit.mapper.HabitDAO;
import com.bing.habit.entity.Habit;
import com.bing.habit.model.constant.CachePrefix;
import com.bing.habit.service.ClockInLogService;
import com.bing.habit.service.ClockInRecordService;
import com.bing.habit.service.HabitService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class HabitServiceImpl implements HabitService {

    @Autowired
    HabitDAO habitDAO;
    @Autowired
    ClockInRecordService clockInRecordService;
    @Autowired
    ClockInLogService clockInLogService;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public boolean addOrUpdate(Habit habit) {
        int hid = habit.getId();
        int uid = habit.getUid();
        String habitName = habit.getName();

        // 新增习惯|习惯库不存在  与我现有习惯同名 return fale
        if (isExist(uid, habitName) && hid == 0) {
            return false;
        } else if (isExist(uid, habitName) && hid != 0) {//编辑习惯
            habitDAO.updateById(habit);
            return true;
        } else { //新增习惯
            habit.setCreateTime(new Date());
            habitDAO.insert(habit);
            return true;
        }
    }

    /**
     * @description: 删除习惯-删除该习惯下的打卡记录和日志信息
     * @author: xujiabing
     * @date: 2024-09-28 19:54
     * @param: id
     * @return: void
     */
    @Override
    @Transactional
    public void delete(int id) {
        try {
            //删除习惯
            habitDAO.deleteById(id);
            //查询是否存在习惯打卡记录
            List<ClockinRecord> records = clockInRecordService.queryByHabitId(id);
            //存在打卡记录才删除
            if (!records.isEmpty()) {
                List<Integer> ids = records.stream()
                        .map(ClockinRecord::getId).collect(Collectors.toList());
                clockInRecordService.deleteBatchIds(ids);
            }
            //查询是否存在打卡日志
            List<ClockinLog> clockinLogs = clockInLogService.listByHabit(id);
            if (!clockinLogs.isEmpty()) {
                //异步删除打卡日志中上传的图片
                //改成定时任务或者延时队列
//                for (ClockinLog clockinLog : clockinLogs) {
//                    if (StringUtils.isNotBlank(clockinLog.getImageUrl())) {
//                        clockInLogService.delUploadFile(clockinLog.getImageUrl());
//                    }
//                }
                //stream 获取习惯下的图片url集合
                List<String> imgUrls = clockinLogs.stream()
                        .map(ClockinLog::getImageUrl).collect(Collectors.toList());
                //存放到redis中,key为习惯id {HABIT_KEY}_97
                redisTemplate.opsForValue()
                        .set(CachePrefix.HABIT_KEY.getPrefix() + clockinLogs.get(0).getHid() ,imgUrls );
                //删除日志记录
                List<Integer> ids = clockinLogs.stream()
                        .map(ClockinLog::getId).collect(Collectors.toList());
                clockInLogService.deleteBatchIds(ids);
            }
        } catch (Exception e) {
            throw new BusinessException("删除习惯过程异常");
        }

    }

    @Override
    public Habit get(int id) {
        return habitDAO.selectById(id);
    }

    @Override
    public List<Habit> listByUid(int uid) {
        return habitDAO.findAllByUid(uid);
    }

    @Override
    public boolean isExist(int uid, String habitName) {
        Habit habit = habitDAO.findByUidAndName(uid, habitName);
        if (habit == null) {
            return false;
        }
        return true;

    }
}
